// import * as Lodash from 'lodash';

export const pgSql = (options) => {
  const {  tableName } = options;
  const contentTem = content(options);
  return `
  -- Drop table if exists
  DROP TABLE IF EXISTS public.${tableName};
  -- Create table in PostgreSQL
  CREATE TABLE public.${tableName} (
  ${contentTem}
  );
  -- Comments (PostgreSQL style)
${contentComments(options)}
`;
};
function content(options) {
  const { columns } = options;
  columns.sort((a, b) => b.isPk - a.isPk); //保证主键始终在第一个

  const defs: string[] = [];
  columns.forEach((column) => {
    const {  javaField, isPk, columnType, columnComment } = column;
    const filed = convertToSnakeCase(javaField);
    // const type = lowercaseFirstLetter(javaType);

    if (isPk == '1') {
      const isInt =
        typeof columnType === 'string' && columnType.toLowerCase().includes('int');
      let line = `\t${filed} ${columnType}`;
      if (isInt) {
        line += ` GENERATED BY DEFAULT AS IDENTITY`;
      }
      line += ` PRIMARY KEY`;
      if (columnComment) {
        line += ` -- ${columnComment}`;
      }
      defs.push(line);
    } else  {
      let line = `\t${filed} ${columnType}`;
      const defaultVal = getColumnDefault(column);
      if (defaultVal !== undefined && defaultVal !== null) {
        line += ` DEFAULT ${defaultVal}`;
      }
      if (columnComment) {
        line += ` -- ${columnComment}`;
      }
      defs.push(line);
    }
  });

  return defs.join(',\n');
};
function convertToSnakeCase(str) {
  return str.replace(/([A-Z])/g, '_$1').toLowerCase();
}
function contentComments(options) {
  const { columns, tableName } = options;
  columns.sort((a, b) => b.isPk - a.isPk); //保证主键始终在第一个

  const defs: string[] = [];
  columns.forEach((column) => {
    const { javaField, columnComment } = column;
    if (!javaField) return;

    const filed = convertToSnakeCase(javaField);
    if (columnComment && String(columnComment).trim().length > 0) {
      // 转义单引号，避免语法错误
      const commentText = String(columnComment).replace(/'/g, "''");
      defs.push(`COMMENT ON COLUMN public.${tableName}.${filed} IS '${commentText}';`);
    }
  });

  return defs.join('\n');
}
// function lowercaseFirstLetter(str) {
//   if (str.length === 0 || str === 'Date') {
//     return str;
//   }
//   return str.charAt(0).toLowerCase() + str.slice(1);
// }

// 字段默认值
function getColumnDefault(column) {
  if (column.columnType === 'char') {
    return column.columnDefault == '1';
  } else if (column.columnType === 'varchar') {
    return "''";
  } else {
    return column.columnDefault;
  }
}